<template>
  <div class="container">
    <div class="login-form">
      <h3 class="login-title">智慧园区-登录</h3>
      <el-form ref="form" :model="formData" :rules="rules" label-width="auto" style="max-width: 600px">
        <el-form-item label="账号" prop="username">
          <el-input placeholder="请输入账号" v-model="formData.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input  type="password" placeholder="请输入密码" v-model="formData.password"/>
        </el-form-item>
        <el-form-item prop="remember">
          <el-checkbox v-model="formData.remeber">记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login_btn" @click="doLogin()">登录</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { loginAPI } from '@/apis/user';
import { FORMDATA_KEY } from '@/constants';
import router from '@/router';
import { setToken } from '@/utils/auth';
import type { FormInstance } from 'element-plus';
import { onMounted, ref } from 'vue';

const formData = ref({
  username: "demo",
  password: "Hmzs%001",
  remeber:''
})
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}
// 从本地取出数据赋值 
onMounted(() => {
  const jsonStr = localStorage.getItem(FORMDATA_KEY)
  if (jsonStr !== null) {
    const userPassObj = JSON.parse(jsonStr)
    if (userPassObj) {
      formData.value = userPassObj
    }
  }
}) 

const form = ref<FormInstance | undefined>()
const doLogin = () => {
  form.value!.validate(async (valid) => {
    if (valid) {
      const { username, password } = formData.value
      const res = await loginAPI({ username, password })
      // 确保登录流程ok后，并且账号密码正确的
      if (formData.value.remeber) {
        localStorage.setItem(FORMDATA_KEY, JSON.stringify(formData.value))
      } else {
        localStorage.removeItem(FORMDATA_KEY)
      }

      setToken(res.data.token)
      router.replace('/')
      console.log('登录',res.data)
    }
  })
}
</script>

<style scoped lang="scss">
.login-form {
  width: 500px;
  max-height: 400px;
  box-shadow: 0 0 10px gray;
  margin: 100px auto;
  padding: 50px;

  .login-title {
    text-align: center;
    padding: 20px 0;
  }
}
</style>